from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from django.db.models import Sum, Count, Avg
from django.utils import timezone
from datetime import timedelta
from .models import (
    CommissionRule, CommissionRecord,
    Invoice, FinancialReport, PaymentTransaction
)
from .serializers import (
    CommissionRuleSerializer, CommissionRecordSerializer,
    CommissionReportSerializer, InvoiceSerializer,
    InvoiceCreateSerializer, FinancialReportSerializer,
    FinancialReportCreateSerializer, PaymentTransactionSerializer,
    RevenueReportSerializer, ExpenseReportSerializer,
    ProfitReportSerializer, PaymentMethodReportSerializer,
    OutstandingInvoiceSerializer
)
from .filters import (
    CommissionRuleFilter, CommissionRecordFilter,
    InvoiceFilter, FinancialReportFilter, PaymentTransactionFilter
)


class CommissionRuleListView(generics.ListCreateAPIView):
    queryset = CommissionRule.objects.all()
    serializer_class = CommissionRuleSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = CommissionRuleFilter
    ordering_fields = ['name', 'created_at']
    ordering = ['-created_at']


class CommissionRuleDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = CommissionRule.objects.all()
    serializer_class = CommissionRuleSerializer
    permission_classes = [permissions.IsAdminUser]


class CommissionRecordListView(generics.ListAPIView):
    queryset = CommissionRecord.objects.all()
    serializer_class = CommissionRecordSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = CommissionRecordFilter
    ordering_fields = ['created_at', 'commission_amount']
    ordering = ['-created_at']


class CommissionReportView(generics.GenericAPIView):
    permission_classes = [permissions.IsAdminUser]
    
    def get(self, request):
        days = int(request.GET.get('days', 30))
        end_date = timezone.now().date()
        start_date = end_date - timedelta(days=days)
        
        records = CommissionRecord.objects.filter(
            created_at__date__gte=start_date,
            created_at__date__lte=end_date
        )
        
        total_commissions = records.aggregate(
            total=Sum('commission_amount')
        )['total'] or 0
        
        pending_commissions = records.filter(
            status='pending'
        ).aggregate(
            total=Sum('commission_amount')
        )['total'] or 0
        
        paid_commissions = records.filter(
            status='paid'
        ).aggregate(
            total=Sum('commission_amount')
        )['total'] or 0
        
        # 计算平均佣金率
        commission_rate = 0
        if total_commissions > 0:
            total_revenue = records.aggregate(
                total=Sum('order__final_amount')
            )['total'] or 0
            if total_revenue > 0:
                commission_rate = (total_commissions / total_revenue) * 100
        
        report = CommissionReportSerializer({
            'total_commissions': total_commissions,
            'pending_commissions': pending_commissions,
            'paid_commissions': paid_commissions,
            'commission_rate': commission_rate
        }).data
        
        return Response(report)


class InvoiceListView(generics.ListCreateAPIView):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = InvoiceFilter
    ordering_fields = ['issue_date', 'due_date', 'total_amount']
    ordering = ['-issue_date']


class InvoiceDetailView(generics.RetrieveUpdateAPIView):
    queryset = Invoice.objects.all()
    serializer_class = InvoiceSerializer
    permission_classes = [permissions.IsAdminUser]


class InvoiceCreateView(generics.CreateAPIView):
    serializer_class = InvoiceCreateSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        invoice = serializer.save()
        
        # 生成发票编号
        invoice.invoice_number = f"INV-{timezone.now().strftime('%Y%m%d')}-{invoice.id:06d}"
        invoice.save()
        
        return Response(
            InvoiceSerializer(invoice).data,
            status=status.HTTP_201_CREATED
        )


class FinancialReportListView(generics.ListCreateAPIView):
    queryset = FinancialReport.objects.all()
    serializer_class = FinancialReportSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = FinancialReportFilter
    ordering_fields = ['start_date', 'end_date', 'created_at']
    ordering = ['-created_at']


class FinancialReportDetailView(generics.RetrieveAPIView):
    queryset = FinancialReport.objects.all()
    serializer_class = FinancialReportSerializer
    permission_classes = [permissions.IsAdminUser]


class FinancialReportCreateView(generics.CreateAPIView):
    serializer_class = FinancialReportCreateSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        report = serializer.save()
        
        # 生成财务报告
        self.generate_financial_report(report)
        
        return Response(
            FinancialReportSerializer(report).data,
            status=status.HTTP_201_CREATED
        )
    
    def generate_financial_report(self, report):
        from orders.models import Order
        
        # 获取指定时间段的订单
        orders = Order.objects.filter(
            created_at__date__gte=report.start_date,
            created_at__date__lte=report.end_date,
            status__in=['completed', 'delivered']
        )
        
        # 计算收入
        total_revenue = orders.aggregate(
            total=Sum('final_amount')
        )['total'] or 0
        
        book_sales = orders.aggregate(
            total=Sum('items__subtotal')
        )['total'] or 0
        
        shipping_income = orders.aggregate(
            total=Sum('shipping_fee')
        )['total'] or 0
        
        # 计算成本
        book_costs = orders.aggregate(
            total=Sum('items__quantity') * Avg('items__book__cost_price')
        )['total'] or 0
        
        shipping_costs = orders.aggregate(
            total=Sum('shipping_fee') * 0.7  # 假设运费成本为70%
        )['total'] or 0
        
        # 计算佣金
        commissions = CommissionRecord.objects.filter(
            created_at__date__gte=report.start_date,
            created_at__date__lte=report.end_date
        ).aggregate(
            total=Sum('commission_amount')
        )['total'] or 0
        
        # 计算净利润
        total_expenses = book_costs + shipping_costs + commissions
        net_profit = total_revenue - total_expenses
        
        # 更新报告
        report.total_revenue = total_revenue
        report.book_sales = book_sales
        report.shipping_income = shipping_income
        report.total_expenses = total_expenses
        report.book_costs = book_costs
        report.shipping_costs = shipping_costs
        report.commissions = commissions
        report.net_profit = net_profit
        report.save()


class PaymentTransactionListView(generics.ListAPIView):
    queryset = PaymentTransaction.objects.all()
    serializer_class = PaymentTransactionSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = PaymentTransactionFilter
    ordering_fields = ['created_at', 'amount', 'status']
    ordering = ['-created_at']


class PaymentTransactionDetailView(generics.RetrieveAPIView):
    queryset = PaymentTransaction.objects.all()
    serializer_class = PaymentTransactionSerializer
    permission_classes = [permissions.IsAdminUser]


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def revenue_report(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    revenue_data = Order.objects.filter(
        created_at__date__gte=start_date,
        created_at__date__lte=end_date,
        status__in=['completed', 'delivered']
    ).annotate(
        date=TruncDate('created_at')
    ).values('date').annotate(
        revenue=Sum('final_amount'),
        orders=Count('id')
    ).annotate(
        average_order_value=Avg('final_amount')
    ).order_by('date')
    
    serializer = RevenueReportSerializer(revenue_data, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def expense_report(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    # 这里需要实现具体的费用计算逻辑
    # 简化版本
    expense_data = []
    for i in range(days):
        date = start_date + timedelta(days=i)
        expense_data.append({
            'date': date,
            'book_costs': 0,
            'shipping_costs': 0,
            'commissions': 0,
            'operational_costs': 0,
            'total_expenses': 0
        })
    
    serializer = ExpenseReportSerializer(expense_data, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def profit_report(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    # 获取收入和费用数据
    revenue_data = Order.objects.filter(
        created_at__date__gte=start_date,
        created_at__date__lte=end_date,
        status__in=['completed', 'delivered']
    ).annotate(
        date=TruncDate('created_at')
    ).values('date').annotate(
        revenue=Sum('final_amount')
    )
    
    # 简化的费用计算
    profit_data = []
    for item in revenue_data:
        expenses = item['revenue'] * 0.7  # 假设费用率为70%
        profit = item['revenue'] - expenses
        profit_margin = (profit / item['revenue'] * 100) if item['revenue'] > 0 else 0
        
        profit_data.append({
            'date': item['date'],
            'revenue': item['revenue'],
            'expenses': expenses,
            'profit': profit,
            'profit_margin': profit_margin
        })
    
    serializer = ProfitReportSerializer(profit_data, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def payment_method_report(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    payment_data = Order.objects.filter(
        created_at__date__gte=start_date,
        created_at__date__lte=end_date,
        status__in=['completed', 'delivered']
    ).values('payment_method').annotate(
        total_amount=Sum('final_amount'),
        transaction_count=Count('id')
    ).annotate(
        average_amount=Avg('final_amount')
    ).order_by('-total_amount')
    
    serializer = PaymentMethodReportSerializer(payment_data, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def outstanding_invoices(request):
    from datetime import date
    
    outstanding = Invoice.objects.filter(
        status='pending',
        due_date__lt=date.today()
    ).values(
        'invoice_number',
        'order__order_number',
        'amount',
        'due_date'
    ).annotate(
        days_overdue=date.today() - F('due_date')
    ).order_by('-due_date')
    
    serializer = OutstandingInvoiceSerializer(outstanding, many=True)
    return Response(serializer.data)
